package com.molichuxing.services.infrastructure.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.molichuxing.framework.exception.BizException;
import com.molichuxing.framework.result.ResponseCodeEnum;
import com.molichuxing.framework.result.ResponseResult;
import com.molichuxing.framework.utils.CollectionUtils;
import com.molichuxing.framework.utils.StringUtil;
import com.molichuxing.services.business.dto.response.AlarmInfoDto;
import com.molichuxing.services.business.dto.response.CarWarnConfigDto;
import com.molichuxing.services.infrastructure.dto.request.create.CarsControlLogsBeanDto;
import com.molichuxing.services.infrastructure.dto.response.IovCarOfflineAlarm;
import com.molichuxing.services.infrastructure.dto.response.IovMileageDto;
import com.molichuxing.services.infrastructure.dto.response.IovResponseDto;
import com.molichuxing.services.infrastructure.dto.response.IovTrajectoryDto;
import com.molichuxing.services.infrastructure.service.IovCarService;
import com.molichuxing.services.infrastructure.service.CarsControlLogsService;
import com.molichuxing.services.property.IovCarControlOperateTypeEnum;
import com.molichuxing.services.property.IovTrajectoryEnum;
import com.molichuxing.services.util.IovPropertyUtils;
import com.molichuxing.services.util.IovUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author liuruifeng
 * 车联网车辆服务
 * 2019-10-17
 */
@Service("iovCarService")
public class IovCarServiceImpl implements IovCarService {
    private static final Logger logger = LoggerFactory.getLogger(IovCarServiceImpl.class);

    @Resource
    private IovUtils iovUtils;
    @Resource
    private CarsControlLogsService carsControlLogsService;

    @Override
    public ResponseResult<Map<String, IovMileageDto>> getMileageByVins(List<String> vinList) throws Exception {
        ResponseResult<Map<String, IovMileageDto>> result = new ResponseResult<Map<String, IovMileageDto>>();
        if (CollectionUtils.isEmpty(vinList)) {
            return result.error("参数不能为空");
        }

        Map<String, String> paramMap = new HashMap<>();
        StringBuffer sb = new StringBuffer();
        for (String vin : vinList) {
            sb.append(vin);
            sb.append(",");
        }
        paramMap.put("vinList", sb.substring(0, sb.length() - 1));

        IovResponseDto iovResult = IovUtils.doGet(IovPropertyUtils.GET_MILEAGE_BY_VIN, paramMap);
        if (!iovResult.getFlag()) {
            return result.error(iovResult.getCode(), iovResult.getMessage());
        }

        if (!StringUtil.isEmpty(iovResult.getData())) {
            List<IovMileageDto> list1 = JSONObject.parseArray(iovResult.getData(), IovMileageDto.class);
            Map<String, IovMileageDto> dataMap =
                    list1.stream().collect(Collectors.toMap(IovMileageDto::getVin, iovMileageDto -> iovMileageDto));
            return result.success("成功", dataMap);
        }
        return result.error(iovResult.getCode(), "失败");
    }

    /**
     * 获取车辆当前行驶里程数-仪表盘里程
     *
     * @param vin 车架号
     * @return
     */
    @Override
    public Integer getCurrentMileage(String vin) {
        Integer result = null;
        try {
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("vinList", vin);
            // 调用车联网获取里程数
            IovResponseDto iovResult = IovUtils.doGet(IovPropertyUtils.GET_MILEAGE_BY_VIN, paramMap);
            if (!iovResult.getFlag() || iovResult.getCode() != ResponseCodeEnum.SUCCESS.getCode()) {
                logger.error("[getCurrentMileage]获取车辆(" + vin + ")当前行驶里程数(仪表盘里程)失败：{}",
                        JSONObject.toJSONString(iovResult));
                throw new BizException(iovResult.getCode(), iovResult.getMessage());
            }

            if (StringUtil.isEmpty(iovResult.getData())) {
                logger.error("[getCurrentMileage]获取车辆(" + vin + ")当前行驶里程数(仪表盘里程)失败：{}",
                        JSONObject.toJSONString(iovResult));
                return result;
            }

            List<IovMileageDto> iovMileageDtos = JSONObject.parseArray(iovResult.getData(), IovMileageDto.class);
            if (iovMileageDtos == null || iovMileageDtos.isEmpty()) {
                return result;
            }
            IovMileageDto iovMileageDto = iovMileageDtos.get(0);
            result = iovMileageDto.getMeterOdo();
        } catch (BizException e) {
            throw new BizException(e.getExceptionCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("[getCurrentMileage]获取车辆(" + vin + ")当前行驶里程数(仪表盘里程)异常：", e);
        }
        return result;
    }

    /**
     * 获取车辆当前行驶里程数-仪表盘里程
     *
     * @param vins 车架号集合
     * @return
     */
    @Override
    public Map<String, Integer> getCurrentMileage(List<String> vins) {
        Map<String, Integer> result = null;
        try {
            Map<String, String> paramMap = new HashMap<>();
            StringBuffer sb = new StringBuffer();
            for (String vin : vins) {
                sb.append(vin);
                sb.append(",");
            }
            paramMap.put("vinList", sb.substring(0, sb.length() - 1));
            // 调用车联网获取里程数
            IovResponseDto iovResult = IovUtils.doGet(IovPropertyUtils.GET_MILEAGE_BY_VIN, paramMap);
            if (!iovResult.getFlag() || iovResult.getCode() != ResponseCodeEnum.SUCCESS.getCode()) {
                logger.error("[getCurrentMileage]批量获取车辆当前行驶里程数(仪表盘里程)失败：{}", JSONObject.toJSONString(iovResult));
                throw new BizException(iovResult.getCode(), iovResult.getMessage());
            }

            if (StringUtil.isEmpty(iovResult.getData())) {
                logger.error("[getCurrentMileage]批量获取车辆当前行驶里程数(仪表盘里程)失败：{}", JSONObject.toJSONString(iovResult));
                return result;
            }

            List<IovMileageDto> iovMileageDtos = JSONObject.parseArray(iovResult.getData(), IovMileageDto.class);
            if (iovMileageDtos == null || iovMileageDtos.isEmpty()) {
                return result;
            }
            result = iovMileageDtos.stream()
                    .collect(Collectors.toMap(IovMileageDto::getVin, IovMileageDto::getMeterOdo));
        } catch (BizException e) {
            throw new BizException(e.getExceptionCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("[getCurrentMileage]批量获取车辆当前行驶里程数(仪表盘里程)异常：", e);
        }
        return result;
    }

    /**
     * 获取车辆行驶里程数-实际里程
     *
     * @param vin 车架号
     * @return
     */
    @Override
    public Integer getOdoMileage(String vin) {
        Integer result = null;
        try {
            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("vinList", vin);
            // 调用车联网获取里程数
            IovResponseDto iovResult = IovUtils.doGet(IovPropertyUtils.GET_MILEAGE_BY_VIN, paramMap);
            if (!iovResult.getFlag() || iovResult.getCode() != ResponseCodeEnum.SUCCESS.getCode()) {
                logger.error("[getOdoMileage]获取车辆(" + vin + ")当前行驶里程数(实际里程)失败：{}", JSONObject.toJSONString(iovResult));
                throw new BizException(iovResult.getCode(), iovResult.getMessage());
            }

            if (StringUtil.isEmpty(iovResult.getData())) {
                logger.error("[getOdoMileage]获取车辆(" + vin + ")当前行驶里程数(实际里程)失败：{}", JSONObject.toJSONString(iovResult));
                return result;
            }

            List<IovMileageDto> iovMileageDtos = JSONObject.parseArray(iovResult.getData(), IovMileageDto.class);
            if (iovMileageDtos == null || iovMileageDtos.isEmpty()) {
                return result;
            }
            IovMileageDto iovMileageDto = iovMileageDtos.get(0);
            result = iovMileageDto.getOdo();
        } catch (BizException e) {
            throw new BizException(e.getExceptionCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("[getOdoMileage]获取车辆(" + vin + ")当前行驶里程数(实际里程)异常：", e);
        }
        return result;
    }

    /**
     * 获取车辆当前行驶里程数-实际里程
     *
     * @param vins 车架号集合
     * @return
     */
    @Override
    public Map<String, Integer> getOdoMileage(List<String> vins) {
        Map<String, Integer> result = null;
        try {
            Map<String, String> paramMap = new HashMap<>();
            StringBuffer sb = new StringBuffer();
            for (String vin : vins) {
                sb.append(vin);
                sb.append(",");
            }
            paramMap.put("vinList", sb.substring(0, sb.length() - 1));
            // 调用车联网获取里程数
            IovResponseDto iovResult = IovUtils.doGet(IovPropertyUtils.GET_MILEAGE_BY_VIN, paramMap);
            if (!iovResult.getFlag() || iovResult.getCode() != ResponseCodeEnum.SUCCESS.getCode()) {
                logger.error("[getOdoMileage]批量获取车辆当前行驶里程数(实际里程)失败：{}", JSONObject.toJSONString(iovResult));
                throw new BizException(iovResult.getCode(), iovResult.getMessage());
            }

            if (StringUtil.isEmpty(iovResult.getData())) {
                logger.error("[getOdoMileage]批量获取车辆当前行驶里程数(实际里程)失败：{}", JSONObject.toJSONString(iovResult));
                return result;
            }

            List<IovMileageDto> iovMileageDtos = JSONObject.parseArray(iovResult.getData(), IovMileageDto.class);
            if (iovMileageDtos == null || iovMileageDtos.isEmpty()) {
                return result;
            }
            result = iovMileageDtos.stream().collect(Collectors.toMap(IovMileageDto::getVin, IovMileageDto::getOdo));
        } catch (BizException e) {
            throw new BizException(e.getExceptionCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("[getOdoMileage]批量获取车辆当前行驶里程数(实际里程)异常：", e);
        }
        return result;
    }

    @Override
    public Map<String, Byte> getSoc(List<String> vins) {
        Map<String, Byte> result = null;
        try {
            Map<String, String> paramMap = new HashMap<>();
            StringBuffer sb = new StringBuffer();
            for (String vin : vins) {
                sb.append(vin);
                sb.append(",");
            }
            paramMap.put("vinList", sb.substring(0, sb.length() - 1));
            // 调用车联网获取电量
            IovResponseDto iovResult = IovUtils.doGet(IovPropertyUtils.GET_SOC_BY_VIN, paramMap);
            if (!iovResult.getFlag() || iovResult.getCode() != ResponseCodeEnum.SUCCESS.getCode()) {
                logger.error("[getOdoMileage]批量获取车辆电量失败：{}", JSONObject.toJSONString(iovResult));
                throw new BizException(iovResult.getCode(), iovResult.getMessage());
            }

            if (StringUtil.isEmpty(iovResult.getData())) {
                logger.error("[getOdoMileage]批量获取车辆电量失败：{}", JSONObject.toJSONString(iovResult));
                return result;
            }
            return JSONObject.parseObject(iovResult.getData(), HashMap.class);
        } catch (BizException e) {
            throw new BizException(e.getExceptionCode(), e.getMessage());
        } catch (Exception e) {
            logger.error("[getOdoMileage]批量获取车辆当前行驶里程数(实际里程)异常：", e);
        }
        return result;
    }


    @Override
    public ResponseResult<List<String>> getTrajectoryTime(String vin) {
        ResponseResult<List<String>> result = new ResponseResult<>();
        try {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("num", vin);
            paramMap.put("numType", IovTrajectoryEnum.VIN.getValue());
            // 调用车联网获取里程数
            IovResponseDto iovResult = IovUtils.doPost(IovPropertyUtils.GET_TRAJECTORY_BY_VIN_TIME, paramMap);
            if (!iovResult.getFlag()) {
                return result.error(iovResult.getCode(), iovResult.getMessage());
            }
            return result.success(JSONObject.parseArray(iovResult.getData(), String.class));
        } catch (IOException e) {
            logger.error("[getTrajectoryTime]获取车辆行驶轨迹异常时间段：", e);
        }
        return result;
    }

    @Override
    public ResponseResult<List<IovTrajectoryDto>> getTrajectory(String vin, String startTime, String endTime) {
        ResponseResult<List<IovTrajectoryDto>> result = new ResponseResult<>();
        try {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("num", vin);
            paramMap.put("startTime", startTime);
            paramMap.put("endTime", endTime);
            paramMap.put("numType", IovTrajectoryEnum.VIN.getValue());
            // 调用车联网获取里程数
            IovResponseDto iovResult = IovUtils.doPost(IovPropertyUtils.GET_TRAJECTORY_BY_VIN, paramMap);
            if (!iovResult.getFlag()) {
                return result.error(iovResult.getCode(), iovResult.getMessage());
            }
            return result.success(JSONObject.parseArray(iovResult.getData(), IovTrajectoryDto.class));
        } catch (IOException e) {
            logger.error("[getTrajectory]获取车辆行驶轨迹异常：", e);
        }
        return result;
    }

    /**
     * 指定车辆是否在围栏
     *
     * @param vin     车架号
     * @param fenceId 围栏id
     * @return
     */
    @Override
    public ResponseResult<Boolean> carIsInside(String vin, Long fenceId) throws Exception {
        ResponseResult<Boolean> result = new ResponseResult<>();
        try {
            Map<String, Object> param = new HashMap<>();
            param.put("vin", vin);
            param.put("fenceId", fenceId);

            IovResponseDto iovResult = IovUtils.doPost(IovPropertyUtils.FENCE_IS_INSIDE, param);
            if (!iovResult.getFlag()) {
                return result.error(iovResult.getCode(), iovResult.getMessage());
            }

            return result.success(Boolean.parseBoolean(iovResult.getData()));
        } catch (IOException e) {
            logger.error("[carIsInside]指定车辆是否在围栏异常：", e);
        }
        return result;
    }

    /**
     * 查询失联车辆报警
     *
     * @param vin       车架号
     * @param beginTime 最后通讯时间 开始时间
     * @param endTime   最后通讯时间 结束时间
     * @return
     */
    @Override
    public List<IovCarOfflineAlarm> listOfflineAlarmsByVin(String vin, String beginTime, String endTime, String license) {
        List<IovCarOfflineAlarm> result = null;
        try {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("vin", vin);
            paramMap.put("beginTime", beginTime);
            paramMap.put("endTime", endTime);
            paramMap.put("license", license);
            logger.info("iov查询失联车辆报警入参:{}", paramMap);
            IovResponseDto iovResult = IovUtils.doPost(IovPropertyUtils.OFFLINE_ALARMS_BY_VIM, paramMap);
            logger.info("iov查询失联车辆报警出参:{}", iovResult);
            if (!iovResult.getFlag() || iovResult.getCode() != ResponseCodeEnum.SUCCESS.getCode()) {
                throw new BizException(iovResult.getCode(), iovResult.getMessage());
            }
            if (!StringUtil.isEmpty(iovResult.getData())) {
                result = JSONArray.parseArray(iovResult.getData(), IovCarOfflineAlarm.class);
            }

        } catch (IOException e) {
            logger.error("[listOfflineAlarmsByVin]查询失联车辆报警异常：", e);
        }
        return result;
    }

    /**
     * 获取所有车辆里程
     *
     * @return
     * @throws Exception
     */
    @Override
    public List<IovMileageDto> getMileage() throws Exception {
        List<IovMileageDto> list = null;
        try {
            Map<String, String> paramMap = new HashMap<>();

            long mileageStart = System.currentTimeMillis();
            IovResponseDto iovResult = IovUtils.doGet(IovPropertyUtils.GET_MILEAGE, paramMap);
            long mileageEnd = System.currentTimeMillis();
            long mileageTime = mileageEnd - mileageStart;
            logger.info("查询车联网获取里程时间：" + mileageTime);

            logger.info("调用车联网返回数据：" + JSONObject.toJSONString(iovResult));
            if (!iovResult.getFlag()) {
                throw new BizException(iovResult.getCode(), iovResult.getMessage());
            }

            if (StringUtils.isBlank(iovResult.getData())) {
                return null;
            }
            list = JSONObject.parseArray(iovResult.getData(), IovMileageDto.class);
        } catch (Exception e) {
            logger.error("[getMileage]查询车辆里程异常：", e);
        }
        return list;
    }

    /**
     * 获取车辆是否存在未处理里程异变
     *
     * @param vin 车架号
     * @return
     * @throws Exception
     */
    @Override
    public boolean getIsMileageExAlarms(String vin) throws Exception {
        boolean result = false;
        StringBuffer sb = new StringBuffer();
        try {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("vin", vin);
            sb.append("调用车联网获取车辆是否存在未处理里程异变查询参数：" + paramMap);
            IovResponseDto iovResult = IovUtils.doPost(IovPropertyUtils.MILEAGE_EX_ALARMS, paramMap);
            sb.append("调用车联网获取车辆是否存在未处理里程异变返回值：" + JSONObject.toJSONString(iovResult));
            if (!iovResult.getFlag() || iovResult.getCode() != ResponseCodeEnum.SUCCESS.getCode()) {
                throw new BizException(iovResult.getCode(), iovResult.getMessage());
            }
            // 存在
            List<Object> resList = iovResult.getData() == null ? null : JSONObject.parseArray(iovResult.getData());
            if (resList != null && !resList.isEmpty()) {
                result = true;
            }
        } catch (Exception e) {
            logger.error("[getIsMileageExAlarms]获取车辆(" + vin + ")是否存在未处理里程异变异常:", e);
            result = false;
        } finally {
            logger.info("[getIsMileageExAlarms]" + sb.toString());
        }
        return result;
    }

    @Override
    public List<AlarmInfoDto> getMileageExAlarmsList(String vin, String beginTime, String endTime, String license) {
        List<AlarmInfoDto> alarmInfoDtos = new ArrayList<>();
        StringBuffer sb = new StringBuffer();
        try {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("vin", vin);
            paramMap.put("beginTime", beginTime);
            paramMap.put("endTime", endTime);
            paramMap.put("license", license);
            logger.info("调用车联网获取车辆获取异变接口入参:{}", paramMap);
            IovResponseDto iovResult = IovUtils.doPost(IovPropertyUtils.MILEAGE_EX_ALARMS, paramMap);
            logger.info("调用车联网获取车辆获取异变接口出参:{}", iovResult);
            if (!iovResult.getFlag() || iovResult.getCode() != ResponseCodeEnum.SUCCESS.getCode()) {
                throw new BizException(iovResult.getCode(), iovResult.getMessage());
            }
            // 存在
            if (StringUtils.isBlank(iovResult.getData())) {
                return alarmInfoDtos;
            }
            alarmInfoDtos = JSONObject.parseArray(iovResult.getData(), AlarmInfoDto.class);
        } catch (Exception e) {
            logger.error("[getMileageExAlarmsList]获取车辆(" + vin + ")是否存在未处理里程异变异常:", e);
        } finally {
            logger.info("[getMileageExAlarmsList]" + sb.toString());
        }
        return alarmInfoDtos;
    }

    /**
     * 获取围栏报警
     *
     * @param vin
     * @param beginTime
     * @param endTime
     * @param license
     * @return
     */
    @Override
    public List<AlarmInfoDto> getFenceAlarmList(String vin, String beginTime, String endTime, String license, List<Integer> fenceIds) {
        List<AlarmInfoDto> alarmInfoDtos = new ArrayList<>();
        StringBuffer sb = new StringBuffer();
        try {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("vin", vin);
            paramMap.put("beginTime", beginTime);
            paramMap.put("endTime", endTime);
            paramMap.put("license", license);
            paramMap.put("fenceIds", fenceIds);
            logger.info("调用车联网获取车辆获取围栏报警接口入参:{}", paramMap);
            IovResponseDto iovResult = IovUtils.doPost(IovPropertyUtils.LIST_FENCE_ALARMS, paramMap);
            logger.info("调用车联网获取车辆获取获取围栏报警接口出参:{}", iovResult);
            if (!iovResult.getFlag() || iovResult.getCode() != ResponseCodeEnum.SUCCESS.getCode()) {
                throw new BizException(iovResult.getCode(), iovResult.getMessage());
            }
            // 存在
            if (StringUtils.isBlank(iovResult.getData())) {
                return alarmInfoDtos;
            }
            alarmInfoDtos = JSONObject.parseArray(iovResult.getData(), AlarmInfoDto.class);
        } catch (Exception e) {
            logger.error("[getFenceAlarmList]获取车辆(" + vin + ")是否存在未处理里程异变异常:", e);
        } finally {
            logger.info("[getFenceAlarmList]" + sb.toString());
        }
        return alarmInfoDtos;
    }

    /**
     * 解除车辆控制（车辆解锁）
     *
     * @param vin  车架号
     * @param memo 原因说明
     * @return true：成功，false：失败，null：无需操作
     * @throws Exception
     */
    @Override
    public Boolean modifyCarDecontrol(String vin, String memo) {
        Boolean result = null;
        StringBuffer sb = new StringBuffer();
        try {
            // 车辆解锁前查询车辆当前状态是否需要解锁
            Boolean controlStatus = this.getCarControlStatus(vin);
            if (controlStatus == null || controlStatus) {
                logger.info("车辆(" + vin + ")无需解锁");
                return result;
            }

            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("vin", vin);
            paramMap.put("operateType", IovCarControlOperateTypeEnum.DECONTROL.getValue());
            paramMap.put("memo", "");
            sb.append("调用车联网解除车辆控制（车辆解锁）参数：" + paramMap);
            IovResponseDto iovResult = IovUtils.doPost(IovPropertyUtils.COMMAND_CONTROL, paramMap);
            sb.append("调用车联网解除车辆控制（车辆解锁）返回值：" + JSONObject.toJSONString(iovResult));
            if (!iovResult.getFlag() || iovResult.getCode() != ResponseCodeEnum.SUCCESS.getCode()) {
                throw new BizException(iovResult.getCode(), iovResult.getMessage());
            }
            // 存在
            result = true;
        } catch (BizException e) {
            logger.error("[modifyCarDecontrol]获取车辆(" + vin + ")是否存在未处理里程异变失败:", e);
            result = false;
        } catch (Exception e) {
            logger.error("[modifyCarDecontrol]获取车辆(" + vin + ")是否存在未处理里程异变异常:", e);
            result = false;
        } finally {
            logger.info("[modifyCarDecontrol]" + sb.toString());
        }
        return result;

    }

    /**
     * 查询车辆动力状态
     *
     * @param vin 车架号
     * @return true：开锁状态，false：锁定状态，null：查询失败
     */
    @Override
    public Boolean getCarControlStatus(String vin) {
        Boolean result = null;
        StringBuffer sb = new StringBuffer();
        try {

            Map<String, String> paramMap = new HashMap<>();
            paramMap.put("vinList", vin);
            sb.append("调用车联网查询车辆动力状态参数：" + paramMap);
            IovResponseDto iovResult = IovUtils.doGet(IovPropertyUtils.DYNAMIC_STATE, paramMap);
            sb.append("调用车联网查询车辆动力状态返回值：" + JSONObject.toJSONString(iovResult));
            if (!iovResult.getFlag() || iovResult.getCode() != ResponseCodeEnum.SUCCESS.getCode()) {
                throw new BizException(iovResult.getCode(), iovResult.getMessage());
            }
            if (iovResult.getData() == null) {
                throw new BizException("查询车辆动力状态失败，返回数据为空");
            }
            // 存在
            Map<String, Object> map = JSONObject.parseObject(iovResult.getData(), HashMap.class);
            int res = map.get(vin) == null ? 0 : Integer.parseInt(map.get(vin).toString());
            if (res == 0) {
                result = false;
            } else if (res == 1) {
                result = true;
            }
        } catch (BizException e) {
            logger.error("[getCarControlStatus]获取车辆(" + vin + ")动力状态失败:", e);
        } catch (Exception e) {
            logger.error("[getCarControlStatus]获取车辆(" + vin + ")动力状态异常:", e);
        } finally {
            logger.info("[getCarControlStatus]" + sb.toString());
        }
        return result;
    }


    /**
     * 车辆控制命令
     *
     * @param vin         车架号
     * @param operateType 操作类型  4设为租赁、5设为非租赁、8开启动、9关闭动力
     * @return
     */
    @Override
    public Boolean vehicleControlCommand(String vin, Integer operateType, Integer accountId, String account) {
        Boolean result = false;
        StringBuffer sb = new StringBuffer();
        try {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("vin", vin);
            paramMap.put("operateType", operateType);
            sb.append("调用车联网车辆控制命令入参：" + paramMap);
            IovResponseDto iovResult = IovUtils.doPost(IovPropertyUtils.COMMAND_CONTROL, paramMap);
            sb.append("调用车联网车辆控制命令出参：" + JSONObject.toJSONString(iovResult));
            //添加控车操作日志
            saveVehicleControlLogsBean(vin, operateType, iovResult, accountId, account);
            if (iovResult.getFlag() && iovResult.getCode().equals(ResponseCodeEnum.SUCCESS.getCode())) {
                return true;
            } else {
                return false;
            }
        } catch (Exception e) {
            throw new BizException("调用车联网车辆控制命令失败！");
        } finally {
            logger.info("[vehicleControlCommand]" + sb.toString());
        }
    }

    @Override
    public Map<String, Object> getCarControlStatus() {
        Map<String, Object> map = new HashMap<>();
        StringBuffer sb = new StringBuffer();
        try {

            Map<String, String> paramMap = new HashMap<>();
            sb.append("调用车联网查询车辆动力状态参数：" + paramMap);
            IovResponseDto iovResult = IovUtils.doGet(IovPropertyUtils.DYNAMIC_STATE, paramMap);
            sb.append("调用车联网查询车辆动力状态返回值：" + JSONObject.toJSONString(iovResult));
            if (!iovResult.getFlag() || iovResult.getCode() != ResponseCodeEnum.SUCCESS.getCode()) {
                throw new BizException(iovResult.getCode(), iovResult.getMessage());
            }
            if (iovResult.getData() == null) {
                throw new BizException("查询车辆动力状态失败，返回数据为空");
            }
            // 存在
            return JSONObject.parseObject(iovResult.getData(), HashMap.class);
        } catch (BizException e) {
            logger.error("[getCarControlStatus]获取车辆(" + ")动力状态失败:", e);
        } catch (Exception e) {
            logger.error("[getCarControlStatus]获取车辆(" + ")动力状态异常:", e);
        } finally {
            logger.info("[getCarControlStatus]" + sb.toString());
        }
        return map;
    }

    /**
     * 添加控车操作日志
     *
     * @param operateType 操作类型
     * @param iovResult
     * @param accountId   操作Id
     * @param account     操作账号
     */
    private void saveVehicleControlLogsBean(String vin, Integer operateType, IovResponseDto iovResult, Integer accountId, String account) {
        CarsControlLogsBeanDto dto = new CarsControlLogsBeanDto();
        Date time = Calendar.getInstance().getTime();
        dto.setGmtCreate(time);
        dto.setOptTime(time);
        dto.setOperateType(operateType.byteValue());
        dto.setReceiveResult(JSONObject.toJSONString(iovResult));
        dto.setOperatorName(account);
        dto.setOperatorId(accountId);
        dto.setVin(vin);
        carsControlLogsService.saveVehicleControlLogs(dto);
    }

    /**
     * 车辆解除授权
     */
    @Override
    public Boolean vehicleIsAuth(String vin, Integer accountId, String account) {
        // operateType 操作类型  4设为租赁、5设为非租赁、8开启动、9关闭动力
        Boolean flag = vehicleControlCommand(vin, 5, accountId, account);
        if (!flag) {
            throw new BizException("调用车联网车辆控制命令失败！");
        }
        StringBuffer sb = new StringBuffer();
        try {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("vin", vin);
            //授权状态（0:未授权1:已授权）
            paramMap.put("authorizedStatus", 0);
            sb.append("调用车辆解除授权入参：" + paramMap);
            IovResponseDto iovResult = IovUtils.doPost(IovPropertyUtils.VEHICLE_ISAUTH, paramMap);
            sb.append("调用车辆解除授权出参：" + JSONObject.toJSONString(iovResult));
            if (iovResult.getFlag() && iovResult.getCode().equals(ResponseCodeEnum.SUCCESS.getCode())) {
                return true;
            }
        } catch (Exception e) {
            throw new BizException("调用车辆解除授权失败！");
        } finally {
            logger.info("[vehicleIsAuth]" + sb.toString());
        }
        return false;
    }

    /**
     * 车辆失联
     *
     * @return
     */
    @Override
    public CarWarnConfigDto getCarOfflineConfig() {
        Map<String, Object> paramMap = new HashMap<>();
        CarWarnConfigDto carWarnConfigDto = null;
        try {
            IovResponseDto iovResult = IovUtils.doPost(IovPropertyUtils.CAR_OFFLINE_CONFIG, paramMap);
            logger.info("[getCarOfflineConfig]查询车辆失联报警参数，调用车联网返回数据：" + JSONObject.toJSONString(iovResult));
            if (!iovResult.getFlag() || !iovResult.getCode().equals(ResponseCodeEnum.SUCCESS.getCode())) {
                throw new BizException(iovResult.getCode(), iovResult.getMessage());
            }
            if (iovResult.getData() == null) {
                throw new BizException("查询车辆失联报警参数，调用车联网返回数据为空");
            }
            carWarnConfigDto = JSONObject.parseObject(iovResult.getData(), CarWarnConfigDto.class);
        } catch (Exception e) {
            logger.error("[getCarOfflineConfig]查询车辆失联报警参数异常:", e);
        }
        return carWarnConfigDto;
    }

    /**
     * 修改失联配置
     *
     * @param id
     * @param paramValue
     * @return
     */
    @Override
    public Boolean modifyCarOfflineConfig(Long id, Double paramValue) {
        try {
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("id", id);
            paramMap.put("paramValue", paramValue);
            IovResponseDto iovResult = IovUtils.doPost(IovPropertyUtils.CAR_OFFLINE_CONFIG_MODIFY, paramMap);
            logger.info("[modifyCarOfflineConfig]修改车辆失联报警参数，调用车联网返回数据：" + JSONObject.toJSONString(iovResult));
            if (iovResult.getFlag() && iovResult.getCode().equals(ResponseCodeEnum.SUCCESS.getCode())) {
                return true;
            }
        } catch (Exception e) {
            throw new BizException("修改车辆失联报警参数失败！");
        }
        return false;
    }

}
